const Koa = require("koa");
const puppeteer = require("puppeteer");
const Router = require("koa-router");
const cors = require("@koa/cors");
const cheerio = require("cheerio");
const axios = require("axios");
const path = require("path");
const app = new Koa();
const fs = require("fs");
const nodemailer = require("nodemailer");
const cron = require("node-cron");
const router = new Router();
let title = ""; // 存储获取到的数据

app.use(cors()); // 允许跨域请求

// 获取天气数据
async function getWeather() {
  const browser = await puppeteer.launch({ headless: true }); // 无头模式
  const page = await browser.newPage();

  await page.goto("https://tianqi.qq.com/index.htm", {
    waitUntil: "networkidle2",
  });

  // 获取精确的DOM元素
  const element = await page.waitForSelector("#ls-weather-hour .item");
  // 获取渲染后的完整 HTML
  const renderedHTML = await page.content();
  //   console.log(renderedHTML);

  //   提取天气数据;
  //   在浏览器中执行
  await page.evaluate(async () => {
    return window.getComputedStyle(document.querySelector("#ct-hours")).cssText;
  });

  fs.writeFile(path.join(__dirname, "test.txt"), renderedHTML, (err) => {
    if (err) {
      return console.log("写入失败");
    }
  });
  fs.readFile(path.join(__dirname, "test.txt"), "utf-8", async (err, data) => {
    if (err) {
      return console.log("读取失败");
    }
    const $ = cheerio.load(data);
    const cssLink = $("link[rel='stylesheet']").attr("href");

    // 获取外部 CSS 文件内容
    const cssContent = await axios.get(cssLink);
    fs.writeFileSync(
      path.join(__dirname, "test.css"),
      cssContent.data,
      (err) => {
        if (err) {
          return console.log("写入失败");
        }
      }
    );
    $("#ct-weather  #ls-weather-hour")
      .find("li ")
      .map((index, ele) => {
        const src = $(ele).find("img").attr("src");
        return $(ele).find("img").attr("src", `http://${src}`);
      });

    title = $("#ct-hours").prop("outerHTML");
  });

  await browser.close();
}
// 路由
router.get("/", async (ctx) => {
  await getWeather();
  // 创建传输器
  const transporter = nodemailer.createTransport({
    service: "qq",
    auth: {
      user: "1833817276@qq.com",
      pass: "fhksozqrnwoldhbf",
    },
  });

  // 邮件内容
  const mailOptions = {
    from: "1833817276@qq.com",
    to: "3245534426@qq.com",
    subject: "🖥️每日提醒",
    text: "这是一封每日提醒邮件，请查收。",
    html: `
  <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <link rel="stylesheet" href="./test.css" />
    <style>
      body {
        background-color: #ccc;
      }
      .zks {
        margin: 0 auto;
        background-color: white;
      }
      ol li {
        list-style: none;
        display: inline-block;
      }
    </style>
  </head>
  <body>
    <div class="zks">
    ${title}</div>
   
  </body>
</html>

      `,
  };

  // 定时任务：每天早上 10.30 点发送
  // cron.schedule(
  //   "*/9 * * * * *",
  //   () => {
  //     transporter.sendMail(mailOptions, (error, info) => {
  //       if (error) {
  //         console.error(`❌ 邮件发送失败：${error.message}`);
  //       } else {
  //         console.log(`✅ 邮件已发送：${info.response}`);
  //       }
  //     });
  //   },
  //   {
  //     timezone: "Asia/Shanghai",
  //   }
  // );
  ctx.body = {
    data: {
      title: title,
    },
    status: 200,
    message: "天气数据获取成功",
  };
});

// 启动服务
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000, () => {
  console.log("Server running on http://localhost:3000");
});
